import json
import os

import yaml


def gen_url_map(main_site, md_file):
    with open(md_file, encoding='utf8') as a_yaml_file:
        # 解析yaml
        yaml_data = yaml.load(a_yaml_file, Loader=yaml.FullLoader)

        nav = yaml_data['nav']

        # 目标格式是能复制到html文件的js部分
        sorted_data = {"name": "Android教程", "children": [], "collapsed": False}

        for big_dict in nav:
            load_url(main_site, big_dict, sorted_data)

        url_file = 'android-url-map.json'
        if os.path.exists(url_file):
            os.remove(url_file)
        with open(url_file, 'w') as s:
            s.write(str(json.dumps(sorted_data, ensure_ascii=False)))


def load_url(main_site, input_dict, res_data):
    """
    递归处理数据
    """
    for k1 in input_dict:
        v1 = input_dict[k1]
        if isinstance(v1, list):
            item1 = {"name": k1, "children": []}
            res_data['children'].append(item1)
            for v1_child in v1:
                load_url(main_site, v1_child, item1)
        elif isinstance(v1, str):
            # 此时已经是url了
            final_item = {"name": k1, "url": main_site + v1[0:-3] + "/"}
            res_data['children'].append(final_item)
            return final_item


if __name__ == '__main__':
    print("生成android站的sitemap")
    gen_url_map('https://www.an.rustfisher.com/',
                '/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/mkdocs.yml')
